package com.zx.feign.interceptor;

import com.zx.core.constant.TokenConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.StringUtils;

/**
 * <p>
 * description: Feign请求拦截器，用于在Feign调用时传递认证信息 <br>
 * create: 2025-10-20
 * </p>
 *
 * @author zhou xun
 */
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        try {
            // 从Security上下文中获取认证信息
            var authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.getPrincipal() instanceof Jwt jwt) {
                // 获取JWT令牌
                String token = jwt.getTokenValue();
                if (StringUtils.hasLength(token)) {
                    // 在Feign请求中添加Authorization头
                    template.header(TokenConstants.AUTHENTICATION, TokenConstants.PREFIX + token);
                    log.debug("Feign请求添加认证头: {}", template.url());
                }
            }
        } catch (Exception e) {
            log.warn("Feign请求拦截器处理认证信息时发生异常", e);
        }
    }
}